package com.asia5b.a5mall.middleware.config

import com.asia5b.a5mall.middleware.api.ApiManager
import com.asia5b.a5mall.middleware.model.member.CountryAllModel
import com.asia5b.a5mall.middleware.model.member.CurrencyModel
import com.asia5b.a5mall.middleware.model.member.HouseModel
import com.asia5b.a5mall.middleware.utils.JsonUtil
import com.asia5b.a5mall.middleware.utils.PreferenceHelper
import com.asia5b.a5mall.middleware.utils.appCountrySelect
import com.asia5b.a5mall.middleware.utils.appCurrencySelect
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers

/**
 * Created by zhangyuncai on 2020/5/28.
 * 国家公馆,方便维护
 */
object CountrysRepository {
    val countryAll = 0
    val country = 1
    val currency = 2
    val house = 3
    val lanuage = 4

    private val mustByService = false//强行从后台取值
    private val baseApi = ApiManager.API_BASE
    var countryAllModel: CountryAllModel
        get() {
            return PreferenceHelper.seriToCountry()
        }
        set(value) {
            PreferenceHelper.countryToSeri(value)
        }
    var lastGetTime = 0L


    /**
     * 返回 RMB或¥ 的货币符号
     */
    fun getCurrenCurrencyShort(): String {
        if (currencyIsNull()) {
            update()
        }
        var selectCurrencyShort = ""
        countryAllModel.currency_list?.forEach {
            if (it.country_id == appCurrencySelect) {
                selectCurrencyShort = it.currency_short
            }
        }
        return selectCurrencyShort
    }

    /**
     * 返回 RMB或¥ 的货币符号
     */
    fun getCurrenCurrencyMark(): String {
        return getCurrencySelect().currency_mark
    }

    fun getCurrencySelect(): CurrencyModel {
        if (currencyIsNull()) {
            update()
        }
        var selectCurrencyModel = CurrencyModel()
        countryAllModel.currency_list?.forEach {
            if (it.country_id == appCurrencySelect) {
                selectCurrencyModel = it
            }
        }
        return selectCurrencyModel
    }


    /**
     * 缓存都为空
     */
    fun allIsNull(): Boolean {
        return countryIsNull() && currencyIsNull() && houseIsNull()&& lanuageIsNull()
    }

    /**
     * 缓存国家都为空
     */
    fun countryIsNull(): Boolean {
        return countryAllModel.country_list == null
    }

    /**
     * 缓存货币符号都为空
     */
    fun currencyIsNull(): Boolean {
        return countryAllModel.currency_list == null
    }

    /**
     * 缓存仓库都为空
     */
    fun houseIsNull(): Boolean {
        return countryAllModel.house_list == null
    }

    /**
     * 语言都为空
     */
    fun lanuageIsNull(): Boolean {
        return countryAllModel.language_list == null
    }

    fun <T> anyOb(type: Int): Observable<T> {
        return Observable.just(1)
                .flatMap {
                    if (mustByService ||
                            ((type == CountrysRepository.countryAll && allIsNull())) ||
                            ((type == CountrysRepository.country && countryIsNull())) ||
                            ((type == CountrysRepository.currency && currencyIsNull())) ||
                            ((type == CountrysRepository.house && houseIsNull()))||
                            ((type == CountrysRepository.lanuage && lanuageIsNull()))) {
                        return@flatMap getCountrysByService()
                                .map {
                                    1
                                }
                    } else {//从缓存拿即可
                        return@flatMap Observable.just(1)
                    }
                }
                .map {
                    return@map when (type) {
                        CountrysRepository.countryAll -> {
                            countryAllModel as T
                        }
                        CountrysRepository.country -> {
                            countryAllModel.country_list!! as T
                        }
                        CountrysRepository.currency -> {
                            countryAllModel.currency_list!! as T
                        }
                        CountrysRepository.house -> {
                            var houseModels = arrayListOf<HouseModel>()
                            for (houseModel in countryAllModel.house_list!!) {
                                if (houseModel.country_id == "$appCountrySelect") {
                                    houseModels.add(houseModel)
                                }
                            }
                            houseModels as T
                        }
                        CountrysRepository.lanuage->{
                            countryAllModel.language_list!! as T
                        }
                        else -> {
                            1 as T
                        }
                    }
                }
    }

    /**
     * 获取当前国家,返回数据不可能为空
     */
    fun <T> anyCallback(callback: (T) -> Unit, type: Int): Disposable {
        val subscribe = Observable.just(1)
                .flatMap {
                    if (mustByService ||
                            ((type == CountrysRepository.countryAll && allIsNull())) ||
                            ((type == CountrysRepository.country && countryIsNull())) ||
                            ((type == CountrysRepository.currency && currencyIsNull())) ||
                            ((type == CountrysRepository.house && houseIsNull()))||
                            ((type == CountrysRepository.lanuage && lanuageIsNull()))) {
                        return@flatMap getCountrysByService()
                                .map { 1 }
                    } else {//从缓存拿即可
                        return@flatMap Observable.just(1)
                    }
                }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Consumer {
                    when (type) {
                        CountrysRepository.countryAll -> {
                            callback.invoke(countryAllModel as T)
                        }
                        CountrysRepository.country -> {
                            callback.invoke(countryAllModel.country_list!! as T)
                        }
                        CountrysRepository.currency -> {
                            callback.invoke(countryAllModel.currency_list!! as T)
                        }
                        CountrysRepository.house -> {
                            callback.invoke(countryAllModel.house_list!! as T)
                        }
                        CountrysRepository.lanuage -> {
                            callback.invoke(countryAllModel.language_list!! as T)
                        }
                    }

                }, Consumer {
                    it.printStackTrace()
                })
        return subscribe
    }


    fun update(callback: Consumer<Int>? = null) {
        val observable = getCountrysByService()
        observable
                .subscribeOn(Schedulers.io())
                .subscribe(Consumer {
                    callback?.accept(it)
                }, Consumer { it.printStackTrace() })
    }

    fun getCountrysByService(): Observable<Int> {
        if ((System.currentTimeMillis() - lastGetTime) < 1000) {
            return Observable.just(1)
        }
        lastGetTime = System.currentTimeMillis()
        return return baseApi.getCountrys()
                .flatMap {
                    countryAllModel = JsonUtil.jsonToAny<CountryAllModel>(it.string(), CountryAllModel::class.java)!!
                    return@flatMap Observable.just(1)
                }

    }
}